package com.ym.medical.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ym.core.rabbit.IMessageSenderSV;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.core.utils.tkmybatis.TKCriteria;
import com.ym.medical.dao.AxbResultDao;
import com.ym.medical.domain.entity.AxbResultEntity;
import com.ym.medical.domain.entity.CounsellingRoomEntity;
import com.ym.medical.domain.entity.HuaweiReturnParamEntity;
import com.ym.medical.domain.entity.InquiryOrderEntity;
import com.ym.medical.domain.entity.OrderFlowRecordEntity;
import com.ym.medical.domain.vo.PhoneNotStopVo;
import com.ym.medical.domain.vo.RecordAndTimeVo;
import com.ym.medical.enums.CounsellingRoomStateEnum;
import com.ym.medical.enums.InquiryOrderStateEnum;
import com.ym.medical.enums.OrderFlowRecordSatusEnum;
import com.ym.medical.service.IAxbResultSV;
import com.ym.medical.service.ICounsellingRoomSV;
import com.ym.medical.service.IHuaweiReturnParamSV;
import com.ym.medical.service.IInquiryOrderSV;
import com.ym.medical.service.IOrderFlowRecordSV;
import com.ym.medical.service.task.HuaWeiShutDownPhoneTask;
import com.ym.medical.service.task.VoiceUploadTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ComputerName:DESKTOP-ANGHV23
 * Author:wenbo
 * Date: 2019-07-01
 * Time: 16:09:47
 * 服务实现类
 */
@Service("AxbResultSVImpl")
@Transactional(rollbackFor = Exception.class)
public class AxbResultSVImpl extends BaseSVImpl<AxbResultEntity, AxbResultDao> implements IAxbResultSV {

	private static Logger logger = LoggerFactory.getLogger(AxbResultSVImpl.class);

	@Autowired
	private IHuaweiReturnParamSV iHuaweiReturnParamSV;

	@Autowired
	private IMessageSenderSV messageSenderSV;

	@Autowired
	private IInquiryOrderSV inquiryOrderSV;

	@Autowired
	private ICounsellingRoomSV iCounsellingRoomSV;

	@Autowired
	private IOrderFlowRecordSV iOrderFlowRecordSV;






	/**
	 * 应答类型值
	 */
	private static final String ANSWER = "answer";

	private static final String FEE = "fee";

	private static final String EVENT_TYPE = "eventType";

	private static final String STATUS_INFO = "statusInfo";

	private static final String FEE_LST = "feeLst";

	/**
	 * 查询绑定状态
	 *
	 * @param doctPhone
	 * @param appointTime
	 * @return
	 */
	@Override
	public AxbResultEntity selectBindState(String doctPhone, Date appointTime) {
		AxbResultEntity axbResult = mapper.selectBindState(doctPhone, appointTime);
		return axbResult;
	}

	/**
	 * 服务器异常宕机未挂机订单列表
	 *
	 * @return
	 */
	@Override
	public List<PhoneNotStopVo> selectNotStopOrder() {
		return mapper.selectNotStopOrder();
	}

	/***
	 * 华为回调参数处理
	 * @param jsonObject
	 */
	@Override
	@Async
	public void paseParams(JSONObject jsonObject) {
		if (FEE.equals(jsonObject.get(EVENT_TYPE))) {
			JSONArray jsonArray = jsonObject.getJSONArray(FEE_LST);
			for (Object obj : jsonArray) {
				HuaweiReturnParamEntity param = JSON.parseObject(obj.toString(), HuaweiReturnParamEntity.class);
				param.setUpTime(new Date());
				logger.info("====================>" + param);
				iHuaweiReturnParamSV.insert(param);

			}
		}
		if (ANSWER.equals(jsonObject.getString(EVENT_TYPE))) {
			logger.info("华为电话应答事件触发");
			JSONObject json = jsonObject.getJSONObject(STATUS_INFO);
			//应答后开始计时挂断
			String subscriptionId = json.getString("subscriptionId");
			//通话链路标识
			String sessionId = json.getString("sessionId");
			AxbResultEntity result = mapper.selectOneByExample(TK.select(AxbResultEntity.class)
			.where().andEqualTo(AxbResultEntity::getSubscriptionId,subscriptionId).end());
			Long ioId = result.getIoId();
			result.setSessionId(sessionId);
			mapper.updateByPrimaryKeySelective(result);
			int maxDuration = result.getDuration();
			//订单状态 完成
			TKCriteria<InquiryOrderEntity, Object> model2 = TK.selectWhere(InquiryOrderEntity.class).andEqualTo(InquiryOrderEntity::getId, ioId)
					.andEqualTo(InquiryOrderEntity::getIoState, InquiryOrderStateEnum.COMPLETE.getKey());
			//咨询室状态 完结
			TKCriteria<CounsellingRoomEntity, Object> model3 = TK.selectWhere(CounsellingRoomEntity.class).andEqualTo(CounsellingRoomEntity::getIoId, ioId);
			CounsellingRoomEntity room = new CounsellingRoomEntity();
			room.setCourState(CounsellingRoomStateEnum.HAS_ENDED.getKey());


			//更改询室状态  已回复
			CounsellingRoomEntity room2 = new CounsellingRoomEntity();
			room2.setCourState(CounsellingRoomStateEnum.HAVE_A_REPLY.getKey());
			room2.setCourTimeEnd(new Date());
			iCounsellingRoomSV.updateByParams(room2, model3.end());

			//流转表   已结单
			TKCriteria<OrderFlowRecordEntity, Object> model4 = TK.selectWhere(OrderFlowRecordEntity.class).andEqualTo(OrderFlowRecordEntity::getOrderId, ioId);
			OrderFlowRecordEntity orderFlowRecord = new OrderFlowRecordEntity();
			orderFlowRecord.setStatus(OrderFlowRecordSatusEnum.HAVE_STATEMENTS.getKey());

			com.alibaba.fastjson.JSONObject params = new com.alibaba.fastjson.JSONObject();
			params.put("sessionId", sessionId);
			params.put("model2", model2);
			params.put("orderFlowRecord", orderFlowRecord);
			params.put("model4", model4);
			params.put("room", room);
			params.put("model3", model3);
			HuaWeiShutDownPhoneTask task = new HuaWeiShutDownPhoneTask("华为应答事件挂机触发", TimeUnit.SECONDS.toMillis(maxDuration), params);

			com.alibaba.fastjson.JSONObject params2 = new com.alibaba.fastjson.JSONObject();
			params2.put("ioId", ioId);
			VoiceUploadTask task2 = new VoiceUploadTask("录音文件上传", TimeUnit.SECONDS.toMillis(maxDuration + 30), params2);
			//录音文件实时上传处理
			messageSenderSV.sendDelayTask(task);
			messageSenderSV.sendDelayTask(task2);

			CounsellingRoomEntity counsellingRoom = iCounsellingRoomSV.selectOne(
					TK.select(CounsellingRoomEntity.class).where().andEqualTo(CounsellingRoomEntity::getIoId,ioId)
					.andEqualTo(CounsellingRoomEntity::getCourState,CounsellingRoomStateEnum.HAS_ENDED.getKey()).end());

			if (counsellingRoom != null) {
				return;
			}
			inquiryOrderSV.updateDocDivide(ioId);
			logger.info("====================>华为应答事件 + 医患账户更改");
		}
	}

	/**
	 * 录音文件信息
	 *
	 * @param ioId
	 * @return
	 */
	@Override
	public List<RecordAndTimeVo> selectRecordInfo(Long ioId) {
		return mapper.selectRecordInfo(ioId);
	}
}
